package com.tzf.msst.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tzf.msst.common.BaseResponse;
import com.tzf.msst.common.ErrorCode;
import com.tzf.msst.common.ResultUtils;
import com.tzf.msst.exception.BusinessException;
import com.tzf.msst.exception.ThrowUtils;
import com.tzf.msst.model.dto.userCollectQst.UserCollectQstAddRequest;
import com.tzf.msst.model.dto.userCollectQst.UserCollectQstQueryRequest;
import com.tzf.msst.model.dto.userCollectQst.UserCollectQstUpdateRequest;
import com.tzf.msst.model.entity.User;
import com.tzf.msst.model.entity.UserCollectQst;
import com.tzf.msst.model.vo.UserCollectQstVO;
import com.tzf.msst.service.UserCollectQstService;
import com.tzf.msst.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 用户收藏接口
 */
@RestController
@RequestMapping("/collect")
@Slf4j
public class UserCollectQstController {

    @Resource
    private UserCollectQstService userCollectQstService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建用户收藏
     *
     * @param userCollectQstAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Boolean> addUserCollectQst(@RequestBody UserCollectQstAddRequest userCollectQstAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userCollectQstAddRequest == null, ErrorCode.PARAMS_ERROR);
        // 获取当前用户信息
        User loginUser = userService.getLoginUser(request);
        // 创建收藏实体
        UserCollectQst userCollectQst = new UserCollectQst();
        userCollectQst.setUserId(loginUser.getId());
        userCollectQst.setIsCollection(1);
        userCollectQst.setQuestionId(userCollectQstAddRequest.getQuestionId());
        userCollectQst.setCollectTime(new Date());
        // 写入数据库
        try {
            // 构造查询条件
            LambdaQueryWrapper<UserCollectQst> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserCollectQst::getUserId, loginUser.getId());
            queryWrapper.eq(UserCollectQst::getQuestionId, userCollectQstAddRequest.getQuestionId());
            // 先查询数据库中是否存在相关记录
            UserCollectQst existUserCollectQst = userCollectQstService.getOne(queryWrapper);
            // 如果存在,则执行更新操作,将收藏状态改为1
            if (existUserCollectQst != null) {
                LambdaUpdateWrapper<UserCollectQst> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(UserCollectQst::getUserId, existUserCollectQst.getUserId());
                updateWrapper.eq(UserCollectQst::getQuestionId, existUserCollectQst.getQuestionId());
                updateWrapper.set(UserCollectQst::getCollectTime, new Date());
                updateWrapper.set(UserCollectQst::getIsCollection, 1);
                userCollectQstService.update(updateWrapper);
            } else {
                // 如果不存在,则创建新的收藏记录
                userCollectQstService.save(userCollectQst);
            }
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.HAS_COLLECT);
        }
        // 返回收藏成功状态
        return ResultUtils.success(true);
    }

    @PostMapping("/exist")
    public BaseResponse<Boolean> existUserCollectQst(@RequestBody UserCollectQstAddRequest userCollectQstAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userCollectQstAddRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = null;
        try {
            loginUser = userService.getLoginUser(request);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        if (loginUser == null) {
            return ResultUtils.success(false);
        }
        LambdaQueryWrapper<UserCollectQst> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserCollectQst::getUserId, loginUser.getId());
        queryWrapper.eq(UserCollectQst::getIsCollection, 1);
        queryWrapper.eq(UserCollectQst::getQuestionId, userCollectQstAddRequest.getQuestionId());
        // 写入数据库
        UserCollectQst userCollectQst = userCollectQstService.getOne(queryWrapper);
        // 返回新写入的数据 id
        return ResultUtils.success(userCollectQst != null);
    }

    /**
     * 更新用户收藏
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> updateUserCollectQst(@RequestBody UserCollectQstUpdateRequest userCollectQstUpdateRequest, HttpServletRequest request) {
        if (userCollectQstUpdateRequest == null || userCollectQstUpdateRequest.getQuestionId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long questionId = userCollectQstUpdateRequest.getQuestionId();
        User loginUser = userService.getLoginUser(request);
        Long id = loginUser.getId();
        LambdaUpdateWrapper<UserCollectQst> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(UserCollectQst::getUserId, id);
        updateWrapper.eq(UserCollectQst::getQuestionId, questionId);
        updateWrapper.set(UserCollectQst::getIsCollection, 0);
        // 操作数据库
        boolean result = userCollectQstService.update(updateWrapper);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }


    /**
     * 分页获取当前登录用户创建的用户收藏列表
     *
     * @param userCollectQstQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<UserCollectQstVO>> listMyUserCollectQstVOByPage(@RequestBody UserCollectQstQueryRequest userCollectQstQueryRequest,
                                                                             HttpServletRequest request) {
        ThrowUtils.throwIf(userCollectQstQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        userCollectQstQueryRequest.setUserId(loginUser.getId());
        long current = userCollectQstQueryRequest.getCurrent();
        long size = userCollectQstQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        //Page<UserCollectQst> userCollectQstPage = userCollectQstService.page(new Page<>(current, size),
        //        userCollectQstService.getQueryWrapper(userCollectQstQueryRequest));
        // 获取封装类
        //return ResultUtils.success(userCollectQstService.getUserCollectQstVOPage(userCollectQstPage, request));
        return null;
    }
}
